package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.core.helper.DictHelper;
import com.bifang.module.system.core.dao.service.SysDictService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.enums.EduAreaCodeEnum;
import com.jwsoft.manager.common.enums.SendStatusEnum;
import com.jwsoft.manager.common.vo.eduMessageModelParams.SmsParamsVo;
import com.jwsoft.manager.common.vo.eduSendContent.EduSendContentVO;
import com.jwsoft.manager.common.vo.eduSendMessage.EduSendMessageKeyVO;
import com.jwsoft.manager.common.vo.eduSendMessage.EduSendMessageQueryVO;
import com.jwsoft.manager.common.vo.eduSendMessage.EduSendMessageVO;
import com.jwsoft.manager.core.dao.model.EduSendContent;
import com.jwsoft.manager.core.dao.model.EduSendMessage;
import com.jwsoft.manager.core.dao.model.EduSendMessageModel;
import com.jwsoft.manager.core.dao.service.EduSchoolService;
import com.jwsoft.manager.core.dao.service.EduSendContentService;
import com.jwsoft.manager.core.dao.service.EduSendMessageModelService;
import com.jwsoft.manager.core.dao.service.EduSendMessageService;
import com.jwsoft.manager.core.integration.EduSendMessageIntegration;
import com.jwsoft.manager.core.integration.EduSendMessageModelIntegration;
import com.jwsoft.manager.core.integration.common.impl.EduSmsIntegrationImpl;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.List;

/**
 * 短信发送表业务实现类
 *
 * @author zjl
 * @since 2024-06-21
 */
@ApiService(funcCode = "eduSendMessage", title = "短信发送表")
public class EduSendMessageIntegrationImpl implements EduSendMessageIntegration {

    @Autowired
    public EduSendMessageService eduSendMessageService;
    @Autowired
    public EduSmsIntegrationImpl eduSmsIntegration;
    @Autowired
    public EduHelper eduHelper;
    @Autowired
    public EduSendMessageModelService eduSendMessageModelService;
    @Autowired
    public SysDictService sysDictService;
    @Autowired
    public EduSchoolService eduSchoolService;
    @Autowired
    public EduSendMessageModelIntegration eduSendMessageModelIntegration;
    @Autowired
    public EduSendContentService eduSendContentService;
    @Autowired
    public DictHelper dictHelper;
    @Override
    @OpApi(funcCode = "eduSendMessage0001", title = "短信发送表分页查询", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE)
    public PageInfo<EduSendMessageVO> getList(EduSendMessageQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        if (vo.getYear()==null){
            vo.setYear(eduHelper.thisYear());
        }
        LambdaQueryWrapper<EduSendMessage> queryWrapper = new QueryWrapper<EduSendMessage>().lambda()
                .eq(vo.getYear() != null, EduSendMessage::getYear, vo.getYear())
                .eq(StringUtils.isNotBlank(vo.getAreaCode()), EduSendMessage::getAreaCode, vo.getAreaCode())
                .eq(StringUtils.isNotBlank(vo.getParentPhone()), EduSendMessage::getParentPhone, vo.getParentPhone())
                .eq(StringUtils.isNotBlank(vo.getParentName()), EduSendMessage::getParentName, vo.getParentName())
                .eq(StringUtils.isNotBlank(vo.getSendStatus()), EduSendMessage::getSendStatus, vo.getSendStatus())
                .eq(vo.getEnrollNum() != null, EduSendMessage::getEnrollNum, vo.getEnrollNum());
        List<EduSendMessage> list = eduSendMessageService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduSendMessage> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduSendMessageVO> resultList = Convert.toList(EduSendMessageVO.class, pageInfo.getList());
        // 转义数据字典值
        dictHelper.valueToName(resultList, Arrays.asList(EduAreaCodeEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduSendMessage0002", title = "短信发送表根据主键查询详情", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE)
    public EduSendMessageVO getById(EduSendMessageKeyVO vo) {
        EduSendMessage entity = eduSendMessageService.getById(vo.getMessageId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduSendMessageVO result = Convert.convert(EduSendMessageVO.class, entity);
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "eduSendMessage0003", title = "短信发送表保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduSendMessageVO vo) {
        //主键为空为新增校验

        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "eduSendMessage0004", title = "短信发送表新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduSendMessage0004",
            operationName = "短信发送表新增",
            dataType = "messageId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSendMessageVO add(EduSendMessageVO vo) {
        //保存前校验
        checkSave(vo);
        //保存数据
        EduSendMessage entity = Convert.convert(EduSendMessage.class, vo);
        eduSendMessageService.save(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setMessageId(entity.getMessageId());
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduSendMessage0005", title = "短信发送表修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduSendMessage0005",
            operationName = "短信发送表修改",
            dataType = "messageId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSendMessageVO edit(EduSendMessageVO vo) {
        if (ObjectUtils.isEmpty(vo.getMessageId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduSendMessage oldEntity = eduSendMessageService.getById(vo.getMessageId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduSendMessage entity = Convert.convert(EduSendMessage.class, vo);
        eduSendMessageService.updateById(entity);
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduSendMessage0006", title = "短信发送表根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduSendMessage0006",
            operationName = "短信发送表删除",
            dataType = "messageId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduSendMessageKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getMessageId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduSendMessage entity = eduSendMessageService.getById(vo.getMessageId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduSendMessageService.removeById(vo.getMessageId());
    }

    @Override
    @OpApi(funcCode = "eduSendMessage0007", title = "推送录取信息到短信内容表", funcType = FuncTypeEnum.other)
    @SaveOplog(operationType = "eduSendMessage0007", operationName = "推送录取信息到短信内容表", dataType = "messageId", auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSendMessageVO pushMessageToContent(EduSendMessageVO vo) {
        if (StringUtils.isBlank(vo.getMessageModelNum())){
            throw new AppException("短信模板编号不能为空");
        }
        LambdaQueryWrapper<EduSendMessageModel> modelLambdaQueryWrapper = new QueryWrapper<EduSendMessageModel>().lambda()
                .eq(EduSendMessageModel::getMessageModelNum, vo.getMessageModelNum())
                .eq(EduSendMessageModel::getYear, eduHelper.thisYear());
        EduSendMessageModel messageModel = eduSendMessageModelService.getOne(modelLambdaQueryWrapper,false);
        if (messageModel==null){
            throw new AppException("查询不到该短信模板");
        }
        if (StringUtils.isBlank(vo.getAreaCode())){
            throw new AppException("行政区划不能为空");
        }
        if (vo.getEnrollNum()==null){
            throw new AppException("报名批次不能为空");
        }
        LambdaQueryWrapper<EduSendMessage> queryWrapper = new QueryWrapper<EduSendMessage>().lambda()
                .eq(EduSendMessage::getSendStatus, SendStatusEnum.dfs.getType())
                .eq(EduSendMessage::getPushStatus,"0")
                .eq(EduSendMessage::getYear, eduHelper.thisYear())
                .eq(EduSendMessage::getAreaCode, vo.getAreaCode())
                .eq(EduSendMessage::getEnrollNum,vo.getEnrollNum());
        List<EduSendMessage> sendMessageList = eduSendMessageService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(sendMessageList)){
            for (EduSendMessage sendMessage : sendMessageList){
                SmsParamsVo smsParamsVo = Convert.convert(SmsParamsVo.class, sendMessage);
                String handlerSMS = eduSendMessageModelIntegration.getHandlerSMS(messageModel.getMessageModelNum(), smsParamsVo);
                EduSendContentVO eduSendContentVO = new EduSendContentVO();
                eduSendContentVO.setContent(handlerSMS);
                eduSendContentVO.setMessageModelId(messageModel.getMessageModelId());
                eduSendContentVO.setMessageModelNum(messageModel.getMessageModelNum());
                eduSendContentVO.setSendStatus(sendMessage.getSendStatus());
                eduSendContentVO.setTelephone(sendMessage.getParentPhone());
                eduSendContentVO.setAreaCode(sendMessage.getAreaCode());
                eduSendContentVO.setYear(eduHelper.thisYear());
                if (StringUtils.isNotBlank(messageModel.getSendEndTime())&&StringUtils.isNotBlank(messageModel.getSendStartTime())){
                    eduSendContentVO.setSendStartTime(messageModel.getSendStartTime());
                    eduSendContentVO.setSendEndTime(messageModel.getSendEndTime());
                }
                eduSendContentService.save(Convert.convert(EduSendContent.class, eduSendContentVO));
                //更新推送状态1已推送到短信内容表
                LambdaUpdateWrapper<EduSendMessage> updateWrapper = new UpdateWrapper<EduSendMessage>().lambda()
                        .set(EduSendMessage::getParams1, "1")
                        .eq(EduSendMessage::getMessageId, sendMessage.getMessageId());
                eduSendMessageService.update(updateWrapper);
            }
        }else{
            throw new AppException("查询不到数据");
        }
        return vo;
    }
}
